from tornado.web import asynchronous
from .BaseHandler import BaseHandler
from tornado.gen import coroutine
from tornado.httpclient import AsyncHTTPClient
from extend import helper
import time
import json
import logging

class Hello(BaseHandler):
    @coroutine
    def get_res_data(self, target_url):
        client = AsyncHTTPClient()
        res = yield client.fetch(target_url)
        data = json.loads(res.body)
        return data

    @asynchronous
    @coroutine
    def get(self, *args, **kaws):
        time.sleep(5)
        data = yield self.get_res_data('http://192.168.191.161:9000')
        self.write(data)
        self.finish()
        # self.write('obj')


class Index(BaseHandler):

    def initialize(self, *args, **kaws):
        pass

    def set_default_headers(self):
        pass

    # @asynchronous
    def get(self, *args, **kaws):
        sql = 'select * from access'
        result = self.mysql.findAll(sql)
        obj = dict(id=int(kaws['id']), result=result)
        #obj = json.dumps(obj)
        logging.error('error')
        logging.info('info')
        logging.debug('debug')
        logging.warning('warning')
        self.write(obj)
        self.finish()


class Login(BaseHandler):
    def post(self):
        payload = json.loads(self.request.body)
        self.set_secure_cookie(
            'token',
            payload['username']
        )
        self.write(payload)

    @asynchronous
    def get(self):
        #a = self.get_query_argument('a')
        #count = self.get
        token = self.get_secure_cookie("token")
        self.write(token)
        self.finish()
